package com.yh.dao;

import com.yh.bean.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @Description: Description
 * @Author: 张颖辉(yh)
 * @CreateDate: 2018/5/9 17:08
 * @UpdateUser: 张颖辉(yh)
 * @UpdateDate: 2018/5/9 17:08
 * @UpdateRemark: The modified content
 * @Version: 1.0
 */
@Component
public class UserDaoImpl implements UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public User getUserByUserName(String userName) {
        String sql = "select * from user where user_name=?";
        List<User> list = jdbcTemplate.query(sql, new String[]{userName}, new RowMapper<User>() {

            @Override
            public User mapRow(ResultSet resultSet, int i) throws SQLException {
               User user = new User();
                user.setId(resultSet.getString("id"));
                user.setUserName(resultSet.getString("user_name"));
                user.setPassWord(resultSet.getString("pass_word"));
                user.setNickName(resultSet.getString("nick_name"));
                user.setCreateTime(resultSet.getDate("create_time"));
                return user;
            }
        });
        if (list.size() > 0)
            return list.get(0);
        return null;
    }

    @Override
    public List<String> getRolesByUserId(String userId) {
        String sql = "select role_name from user_role where user_id=?";
        List<String> roles = jdbcTemplate.query(sql, new String[]{userId}, new RowMapper<String>() {
            @Override
            public String mapRow(ResultSet resultSet, int i) throws SQLException {
                return resultSet.getString("role_name");
            }
        });
        return roles;
    }

    /**
     * @param role
     * @Description: 通过角色查权限
     * @Author: 张颖辉(yh)
     * @Date: 2018/5/9 20:46
     * @param:
     * @return:
     * @Version: 1.0
     */
    @Override
    public List<String> getPermissionsByRole(String role) {
        String sql="select permission_name from role_permissions where role_name=?";
        List<String> permissions = jdbcTemplate.query(sql, new String[]{role}, new RowMapper<String>() {
            @Override
            public String mapRow(ResultSet resultSet, int i) throws SQLException {
                return resultSet.getString("permission_name");
            }
        });
        return permissions;
    }
}
